import time

import akshare as ak
import pandas as pd
import pathlib
from pyecharts.charts import Line, Tab
from pyecharts.globals import ThemeType
import pyecharts.options as opts

from 网格计划 import util
import 网格计划.model as model


# 主要分析指数的相关信息
# 指数当前估值情况、指数走势、指数成分股、指数相关指数、指数相关股票、指数相关行业、指数相关概念、指数相关概念股、指数相关概念行业、指数相关概念股票、指数相关概念行业股票、指数相关概念行业股票、指数相关概念行业股票、指数相关概念行业股票、指数相关概念行业股票、指数相关概念行业股票、指数相关概念行业股票、指数相关概念行业股票、指数相关概念行业股票、指数相关概念行业

# 指数走势历史数据
def index_his(stockIdx: model.StockIndexInfo) -> Line:
    max, min, cur = 0, 0, 0
    percent_25, percent_50, percent_75 = 0, 0, 0
    x_data = [] # x轴数据日期
    y_data = [] # y轴数据
    if stockIdx.market == model.Market.H:
        df = ak.stock_hk_index_daily_em(symbol=stockIdx.code)
        rs = df.describe()
        max, min, cur = rs['high']['max'], rs['low']['min'], df.iloc[-1]["latest"]
        percent_25, percent_50, percent_75 = round(rs["latest"]['25%'], 2), round(rs["latest"]['50%'], 2), round(
            rs["latest"]['75%'], 2)
        x_data = df["date"].tolist()
        y_data = df['latest'].tolist()
    elif stockIdx.market == model.Market.A:
        df = ak.index_zh_a_hist(symbol=stockIdx.code)
        rs = df.describe()
        max, min, cur = rs['最高']['max'], rs['最低']['min'], df.iloc[-1]["收盘"]
        percent_25, percent_50, percent_75 = round(rs["收盘"]['25%'], 2), round(rs["收盘"]['50%'], 2), round(
            rs["收盘"]['75%'], 2)
        x_data = df["日期"].tolist()
        y_data = df['收盘'].tolist()

    print(f'{stockIdx.name} 最高:{max} 最低:{min} 当前: {cur}')
    # 绘制图表 - 折线图
    chart = Line(
        # 设置主题、画布宽度、高度等信息
        init_opts=opts.InitOpts(theme=ThemeType.DARK, width="1400px", height="600px"),
    )

    # 全局设置
    chart.set_global_opts(
        title_opts=opts.TitleOpts(title=f'{stockIdx.name} 走势-当前:{cur}'),
        # 工具箱配置
        toolbox_opts=opts.ToolboxOpts(is_show=True),
        # 区域缩放配置
        datazoom_opts=[opts.DataZoomOpts(is_show=True, range_start=0, range_end=100)],
        # y轴配置
        yaxis_opts=opts.AxisOpts(
            min_=round(min * 0.9, 2),  # 设置y轴刻度间隔为20
        )
    )

    chart.add_xaxis(xaxis_data=x_data)  # 添加x轴数据

    chart.add_yaxis(
        series_name=stockIdx.code,
        y_axis=y_data,  # y轴数据
        is_connect_nones=True,  # 连接空数据
        markpoint_opts=opts.MarkPointOpts(
            data=[opts.MarkPointItem(type_="max"), opts.MarkPointItem(type_="min")],
        ),
        markline_opts=opts.MarkLineOpts(
            data=[
                opts.MarkLineItem(name=f"25%-{percent_25}", y=f'{percent_25}'),
                opts.MarkLineItem(name=f"50%-{percent_50}", y=f'{percent_50}'),
                opts.MarkLineItem(name=f"75%-{percent_75}", y=f'{percent_75}'),
            ]
        ),
    )

    return chart


# 获取指数估值历史数据
def index_val_hist_funddb(stockIdx: model.StockIndexInfo, indicator: str = "市盈率") -> Line:
    df = ak.index_value_hist_funddb(symbol=stockIdx.name, indicator=indicator)
    rs = df.describe()
    # print(rs)
    max, min, cur = rs[indicator]['max'], rs[indicator]['min'], df.iloc[-1][indicator]
    percent_25, percent_50, percent_75 = round(rs[indicator]['25%'], 2), round(rs[indicator]['50%'], 2), round(
        rs[indicator]['75%'], 2)
    print(f'{stockIdx.name} {indicator} 最高:{max} 最低:{min} 当前: {df.iloc[-1][indicator]}')
    # 绘制图表 - 折线图
    chart = Line(
        # 设置主题、画布宽度、高度等信息
        init_opts=opts.InitOpts(theme=ThemeType.DARK, width="1400px", height="600px"),
    )

    # 全局设置
    chart.set_global_opts(
        title_opts=opts.TitleOpts(title=f'{stockIdx.name}-{indicator}-当前:{df.iloc[-1][indicator]}'),
        # 工具箱配置
        toolbox_opts=opts.ToolboxOpts(is_show=True),
        # 区域缩放配置
        datazoom_opts=[opts.DataZoomOpts(is_show=True, range_start=0, range_end=100)],
        # y轴配置
        yaxis_opts=opts.AxisOpts(
            min_=round(min * 0.9, 2),  # 设置y轴刻度间隔为20
        )
    )

    chart.add_xaxis(xaxis_data=df["日期"].tolist())  # 添加x轴数据

    # markLineList = []
    # for index, row in gridDf.iterrows():
    #     if row['加仓批次'] == 0:
    #         continue
    #     price = round(row['基金价格'], 3)
    #     markLineList.append(
    #         opts.MarkLineItem(name=f"第{int(row['加仓批次'])}网-回撤:{row['回撤比例%']}%", y=f'{price}'))

    chart.add_yaxis(
        series_name=indicator,
        y_axis=df[indicator].tolist(),  # y轴数据
        is_connect_nones=True,  # 连接空数据
        markpoint_opts=opts.MarkPointOpts(
            data=[opts.MarkPointItem(type_="max"), opts.MarkPointItem(type_="min")],
        ),
        markline_opts=opts.MarkLineOpts(
            data=[
                opts.MarkLineItem(name=f"25%-{percent_25}", y=f'{percent_25}'),
                opts.MarkLineItem(name=f"50%-{percent_50}", y=f'{percent_50}'),
                opts.MarkLineItem(name=f"75%-{percent_75}", y=f'{percent_75}'),
            ]
        ),
    )

    return chart


# 指数对应基金走势
def fund_his(stockIdx: model.StockIndexInfo, startPercent: int = 40, step: float = 5, perMoney: int = 1000) -> Line:
    """
    :param stockIdx:
    :param startPercent: 回撤达到多少开始网格
    :param step: 网格步长
    :param perMoney: 每份金额
    :return:
    """
    startDate = "20010101"
    df = ak.fund_etf_hist_em(symbol=stockIdx.fundList[0].code, start_date=startDate, adjust="qfq")
    rs = df.describe()
    max, min, cur = rs['最高']['max'], rs['最低']['min'], df.iloc[-1]["收盘"]

    gridDf = util.getGridPlan(maxValue=max, minValue=min, step=step, startPercent=startPercent, money=perMoney)

    # 绘制图表 - 折线图
    chart = Line(
        # 设置主题、画布宽度、高度等信息
        init_opts=opts.InitOpts(theme=ThemeType.DARK, width="1400px", height="600px"),
    )

    # 全局设置
    chart.set_global_opts(
        title_opts=opts.TitleOpts(title=f'{stockIdx.fundList[0].name}-{stockIdx.fundList[0].code}-当前:{cur}'),
        # 工具箱配置
        toolbox_opts=opts.ToolboxOpts(is_show=True),
        # 区域缩放配置
        datazoom_opts=[opts.DataZoomOpts(is_show=True, range_start=0, range_end=100)],
        # y轴配置
        yaxis_opts=opts.AxisOpts(
            min_=round(min * 0.9, 2),  # 设置y轴刻度间隔为20
        )
    )

    chart.add_xaxis(xaxis_data=df["日期"].tolist())  # 添加x轴数据

    markLineList = []
    for index, row in gridDf.iterrows():
        if row['批次'] == 0:
            continue
        price = round(row['价格'], 3)
        markLineList.append(
            opts.MarkLineItem(name=f"第{int(row['批次'])}网-回撤:{row['回撤']}%", y=f'{price}'))

    chart.add_yaxis(
        series_name=stockIdx.fundList[0].code,
        y_axis=df['收盘'].tolist(),  # y轴数据
        is_connect_nones=True,  # 连接空数据
        markpoint_opts=opts.MarkPointOpts(
            data=[opts.MarkPointItem(type_="max"), opts.MarkPointItem(type_="min")],
        ),
        markline_opts=opts.MarkLineOpts(
            data=markLineList
        ),

    )
    return chart



if __name__ == "__main__":
    stockIdx = model.GetHSKeJiStockIndexInfo()

    dataDir = pathlib.Path(f'./data/{stockIdx.name}')
    pathlib.Path(dataDir).mkdir(parents=True, exist_ok=True)
    tab = Tab()
    # 指数走势
    chart = index_his(stockIdx)
    tab.add(chart, "指数走势")

    # 指数估值
    # indicatorList = ["市盈率", "市净率", "股息率"]
    # for indicator in indicatorList:
    #     chart = index_val_hist_funddb(stockIdx, indicator)
    #     tab.add(chart, indicator)

    # 基金情况
    step = 5
    chart = fund_his(stockIdx, startPercent=30, step=step)
    tab.add(chart, "网格情况")
    date = time.strftime("%Y%m%d", time.localtime())
    tab.render(f"{dataDir}/指数分析-{stockIdx.name}-{date}-{step}.html")
